const wx2my = require('../../../wx2my');
var base = require('./../../../config.js');
var index = require("../../utils/common.js");
Page({
  data: {
    // 是否线上付押金,
    showDespoit: false,
    price_infos: {},
    yjCost: "",
    imgUrl: "",
    hotel: "",
    room: "",
    day1: "",
    day2: "",
    num: "",
    langTime: "",
    roomLogo:'',
    showModel: false,
    payWay: 4,
    // 上个页面传过来的数据
    data: {},
    // 花呗
    isHuabeiPay: 0,
    // 芝麻信用
    canUseCreditAssessment: my.canIUse('zm-credit-assessment'), //判断组件是否可用
    query: {
      serviceId: '2019111100000000000003791600', // serviceId为商户服务ID，芝麻商户平台可查到
      categoryId: 'CREDIT_HOTEL_ONLINE_ALL', // categoryId为服务类目，芝麻商户平台可查到
      applyAmount: '0.00',
    },
    // 是否选中分期，默认3期
    showHb: 6,
    hbfqsix: 0,
    hbfqtwelve: 0,
    hbfqthree: 0,
    // 金额太小花呗不显示
    isShowhb: false
    // 闪住闪退是否显示
    // isZhimaFundauthPay: 1
  },
  // 用户成功选择服务，必需属性
  onConfirmSuccess(event) {
    let that = this;
    that.setData({
      payWay: 2,
      showDespoit: true,
      showDivideWay: false,
    })
    console.log('settlement');
    console.log(that.data.settlement);
    that.query.applyAmount = that.data.settlement
    const { detail = {} } = event
    const { query = {} } = detail
    console.log({ query });
  },

  // 用户成功取消服务，必需属性
  onCancelSuccess() {
    this.setData({
      payWay: 4,
      showDespoit: false,
      showDivideWay: false,
    })

    // todo
  },

  // 组件内部错误，必需属性，建议写上用来监听组件内部错误
  onError(event) {
    const { detail = {} } = event
    const { query = {}, error = {} } = detail
    console.log('芝麻信用错误打印')
    console.log({ query, error })
    my.alert({
      title: { query, error }
    })
    // todo
  },

  // 组件初始化中，非必需属性
  onIniting() {
    // todo
  },

  // 芝麻信用评估中，非必需属性
  onConfirming() {

    // todo
  },
  // 弹窗显示隐藏
  showModelClick() {
    this.setData({
      showModel: !this.data.showModel
    });
  },
  closeClick() {
    this.setData({
      showModel: false
    });
  },
  // 是否线上支付押金
  selectDespoit() {
    // 如果选择花呗的话和支付宝普通支付,押金不可勾选
    if (this.data.payWay == 3 || this.data.payWay == 4) {
      this.setData({
        showDespoit: false
      })
      return false;
    }
    // 如果选择芝麻信用的话，押金必勾选
    if (this.data.payWay == 2) {
      this.setData({
        showDespoit: true
      })
      return false;
    }
    this.setData({
      showDespoit: !this.data.showDespoit
    })
  },
  // 切换选择支付方式
  payWayChange(e) {
    if (this.data.payWay == 2) {
      return false;
    }
    this.setData({
      payWay: e.currentTarget.dataset.id == 0 ? 1 : e.currentTarget.dataset.id == 1 ? 2 : e.currentTarget.dataset.id == 2 ? 3 : 4,
      showDivideWay: false
    });

    // 如果选择花呗的话和普通支付的话,押金不可勾选
    if (this.data.payWay == 3) {
      this.setData({
        showDespoit: false,
        showDivideWay: true
      })
    } else if (this.data.payWay == 4) {
      this.setData({
        showDespoit: false,
        showDivideWay: false
      })
    }
  },
  onLoad(query) {
    let that = this;
    // console.log(query);
    // console.log('999');
    console.log(my.canIUse('zm-credit-assessment'));
    var outTime = wx2my.getStorageSync(['day2']).data;
    var inTime = wx2my.getStorageSync(['day1']).data;
    var langTime = (new Date(outTime) - new Date(inTime)) / 86400000;
    that.setData({
      imgUrl: wx2my.getStorageSync(['imgUrl1']).data,
      hotel: query.hotel,
      room: query.room,
      roomLogo: query.logo,
      data: JSON.parse(query.data),
      day1: wx2my.getStorageSync(['day1']).data,
      day2: wx2my.getStorageSync(['day2']).data,
      settlement: query.settlement,
      num: query.num,
      langTime: langTime,
      price_infos: JSON.parse(query.price_infos)
    })
    wx2my.newRequest({
      url: base.siteroot,
      data: {
        c: 'entry',
        a: 'wxapp',
        do: 'HbFqcost',
        m: 'zh_jdgjb',
        cost: (query.settlement - JSON.parse(query.data).yj_cost).toFixed(2),
      },
      success: function(res) {
        console.log('HbFqcost1111',res);
        that.setData({
          hbfqsix: res.data.data.hb_fq_six,
          hbfqtwelve: res.data.data.hb_fq_twelve,
        })
      },
      fail: function(res) {
        console.log('HbFqcost2222',res);
      },
    })
  },
  // 选择分期
  divideWayClick(e) {
    this.setData({
      showHb: e.currentTarget.dataset.id
    })
  },
  // 去支付
  submit() {
    let that = this;
    console.log(wx2my.getStorageSync(["userInfo"]).data.uid);
    console.log("111111");
    my.showLoading();
    
    // 普通支付
    index.getDataNew('AddOrder', {
      name: that.data.data.name, //客户姓名
      tel: that.data.data.tel,  //电话
      price: that.data.data.price, //单价
      dd_time: that.data.data.dd_time, //到店时间
      seller_id: that.data.data.seller_id, // 酒店id
      room_id: '25',// f,  //房间id
      user_id: wx2my.getStorageSync(["userInfo"]).data.uid, //用户id
      coupons_id: that.data.data.coupons_id, //优惠券id
      seller_name: that.data.data.seller_name, //房间名称
      seller_address: that.data.data.seller_address, //地址
      coordinates: that.data.data.coordinates,  //经纬度
      arrival_time: that.data.data.arrival_time, //入住时间
      departure_time: that.data.data.departure_time, //离店时间
      num: that.data.data.num, //数量
      room_type: that.data.data.room_type, //房间类型
      bed_type: that.data.data.bed_type,
      days: that.data.data.days,
      dis_cost: (that.data.data.dis_cost * 1 - that.data.data.yj_cost * 1).toFixed(2), //最后折扣后价格
      // yj_cost: that.data.data.yj_cost,
      yhq_cost: that.data.data.yhq_cost, //优惠券价格
      total_cost: that.data.data.total_cost,
      room_logo: that.data.data.room_logo, //房间图片
      yyzk_cost: that.data.data.yyzk_cost,
      hb_id: that.data.data.hb_id,
      hb_cost: that.data.data.hb_cost,
      from_id: that.data.data.from_id, //
      classify: 1,
      type: 4,
      code: that.data.data.code,
      equitycard_id: that.data.data.equitycard_id,  //权益卡id
      equitycard_cost: that.data.data.equitycard_cost
    }, (o) => {
      console.log("这是提交订单")
      console.log(o);
      var t = o.data,
        a = o.data.data.order_id;
      // 当type为4时调起支付
      // if (4 == that.data.payWay) {
      var user_id = wx2my.getStorageSync(['userInfo']).data.uid;
      console.log(user_id);
      console.log("userid");
      console.log(a);
      index.getDataNew('Alipay', {
        user_id,
        order_id: a,
        pay_method: that.data.payWay == 2 ? 2 : 1,//1.普通支付2.预授权
        fundauth_type: that.data.payWay == 2 ? 2 : "",// 芝麻信用预授权为2，普通预授权为1，普通预授权暂无
        is_deposit: that.data.showDespoit ? 1 : 0,// 是否交押金，1有押金，0无
        yj_cost: that.data.showDespoit ? that.data.data.yj_cost : 0,
        hb_fq_num: that.data.payWay == 3 ? that.data.showHb : ""// 选择花呗需上传分期数
      }, (res) => {
        my.hideLoading();
        console.log(res)
        console.log('成功进入Pay...........')
        console.log(res.data.data.trade_no);
        // 普通支付 当payway为花呗和普通支付的时候
        if (that.data.payWay == 4 || that.data.payWay == 3) {
          // 普通支付
          my.tradePay({
            tradeNO: res.data.data.trade_no, // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
            success: (res) => {
              console.log('支付成功。。。。。。。。。。。。')
              console.log(res)
              if (res.resultCode == 9000) {
                wx2my.redirectTo({
                  url: './../order/book?orderid=' + a
                });
              }
              if (res.resultCode == 6001) {
                wx2my.redirectTo({
                  url: "../order/order?activeIndex=1&index=1"
                });
              }
            },
            fail: (err) => {
              console.log("支付失败")
              wx2my.showToast({
                title: "支付失败"
              })
              wx2my.redirectTo({
                url: "../order/order?activeIndex=1&index=1"
              });
            }
          });
        } else if (that.data.payWay == 2) {
          // 调用预授权
          my.tradePay({
            orderStr: res.data.data.trade_no,
            success: (res) => {
              console.log("进入成功预授权");
              console.log(res);
              my.hideLoading();
              if (res.resultCode == 9000) {
                wx2my.redirectTo({
                  url: './../order/book?orderid=' + a
                });

              } else {
                my.alert({
                  content: '支付失败',
                  success: () => {
                    wx2my.redirectTo({
                      url: './../order/book?orderid=' + a
                    });

                  },

                });
              }
            },
            fail: (res) => {
              my.alert({
                content: '支付失败',
              });
              my.hideLoading();
            }
          });
        }

      }, (error) => {
        console.log(error);
        my.hideLoading();
        my.alert({
          title: error + 'alipay'
        });

      });
    }, (err) => {
      my.hideLoading();
      my.alert({
        title: err + 'addorder6'
      });
    })


  },
  onReady: function() { },
  onShow: function() {
    
  },
  onHide: function() { },
  onUnload: function() { },
  onPullDownRefresh: function() { },
  onReachBottom: function() { }

});





